package com.ruoyi.web.controller.system

import com.ruoyi.common.annotation.Log
import com.ruoyi.common.config.RuoYiConfig
import com.ruoyi.common.core.controller.BaseController
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.domain.entity.SysUser
import com.ruoyi.common.core.domain.model.LoginUser
import com.ruoyi.common.enums.BusinessType
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.file.FileUploadUtils
import com.ruoyi.common.utils.file.MimeTypeUtils
import com.ruoyi.framework.web.service.TokenService
import com.ruoyi.system.service.ISysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user/profile")
open class SysProfileController : BaseController() {

    @Autowired
    private lateinit var userService: ISysUserService
    @Autowired
    private lateinit var tokenService: TokenService

    /**
     * 个人信息
     */
    @GetMapping
    open fun profile(): AjaxResult {
        val loginUser: LoginUser = loginUser
        val user: SysUser? = loginUser.user
        val ajax: AjaxResult = AjaxResult.success(user)
        ajax["roleGroup"] = userService.selectUserRoleGroup(loginUser.username)
        ajax["postGroup"] = userService.selectUserPostGroup(loginUser.username)
        return ajax
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    open  fun updateProfile(@RequestBody user: SysUser): AjaxResult {
        val loginUser: LoginUser = loginUser
        val currentUser: SysUser? = loginUser.user
        currentUser?.nickName =user.nickName
        currentUser?.email=user.email
        currentUser?.phonenumber=user.phonenumber
        currentUser?.sex=user.sex
        if (MyStringUtils.isNotEmpty(user.phonenumber) && !userService.checkPhoneUnique(currentUser)) {
            return error("修改用户'" + loginUser.username + "'失败，手机号码已存在")
        }
        if (MyStringUtils.isNotEmpty(user.email) && !userService.checkEmailUnique(currentUser)) {
            return error("修改用户'" + loginUser.username + "'失败，邮箱账号已存在")
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser)
            return success()
        }
        return error("修改个人信息异常，请联系管理员")
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    open  fun updatePwd(oldPassword: String, newPassword: String): AjaxResult {
        var newPwd = newPassword
        val loginUser: LoginUser = loginUser
        val userName: String = loginUser.username
        val password: String = loginUser.password
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误")
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同")
        }
        newPwd = SecurityUtils.encryptPassword(newPwd)
        if (userService.resetUserPwd(userName, newPwd) > 0) {
            // 更新缓存用户密码
            loginUser.user?.password=newPwd
            tokenService.setLoginUser(loginUser)
            return success()
        }
        return error("修改密码异常，请联系管理员")
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    @Throws(Exception::class)
    open  fun avatar(@RequestParam("avatarfile") file: MultipartFile): AjaxResult {
        if (!file.isEmpty) {
            val loginUser: LoginUser = loginUser
            val avatar: String = FileUploadUtils.upload(RuoYiConfig.avatarPath, file, MimeTypeUtils.IMAGE_EXTENSION)
            if (userService.updateUserAvatar(loginUser.username, avatar)) {
                val ajax: AjaxResult = AjaxResult.success()
                ajax["imgUrl"] = avatar
                // 更新缓存用户头像
                loginUser.user?.avatar=avatar
                tokenService.setLoginUser(loginUser)
                return ajax
            }
        }
        return error("上传图片异常，请联系管理员")
    }
}
